package org.gwt.grin.client.features;

import java.util.Map;

import org.gwt.grin.client.Feature;
import org.gwt.grin.client.util.Graphics;
import org.gwt.grin.client.util.Rectangle;

import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.RequiresResize;
import com.google.gwt.user.client.ui.Widget;

public class Bin extends Box {

	private AbsolutePanel widget;

	private Widget child;
	private Widget newChild;

	public Bin(String name) {
		super(name);
	}

	@Override
	protected Feature createClone(Map<Feature, Feature> clones) {
		if (!isSetup() || isActivated) {
			throw new IllegalStateException();
		}
		Bin result = new Bin(null);
		result.setup(x, y, width, height, outlineWidth, outlineColor,
				fillColor, bgImage, null);
		if (scaledBounds != null) {
			result.scaledBounds = new Rectangle(scaledBounds);
		}
		return result;
	}

	public Widget getChild() {
		return child;
	}

	public void setChild(Widget child) {
		this.newChild = child;
		markAsChanged();
	}

	@Override
	protected Widget createWidget() {
		widget = new AbsolutePanel();
		widget.getElement().getStyle().setOverflow(Overflow.HIDDEN);
		return widget;
	}

	@Override
	public void paintFrame(Graphics gc) {
		super.paintFrame(gc);
		if (isChanged()) {
			if (newChild != null) {
				if (child != null) {
					child.removeFromParent();
				}
				child = newChild;
				newChild = null;
				widget.add(child, 0, 0);
				Style style = child.getElement().getStyle();
				style.setRight(0, Unit.PX);
				style.setBottom(0, Unit.PX);
			}
			if (child instanceof RequiresResize) {
				((RequiresResize) child).onResize();
			}
		}
	}
}
